package com.example.loginserver.handler;

import com.example.loginserver.utils.JwtUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;

import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Duration;
import java.util.UUID;

import static com.example.loginserver.domain.Constant.AUTH_TOKEN_PREFIX;

/**
 * 登陆成功的处理器
 */
@Component
@Slf4j
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {

    @Resource
    private RedisTemplate<String, String> redisTemplate;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
//        response.cook
        log.info("登陆成功的cookies：{}",request.getCookies());
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode node = objectMapper.createObjectNode();
        node.put("code", 200);
        node.put("msg", "登陆成功");
        response.setContentType("application/json;charset=UTF-8");

//        创建 token
        String token = JwtUtils.createToken(authentication.getName());


//      创建redis中用户的 key
        String key = AUTH_TOKEN_PREFIX + authentication.getName();

        redisTemplate.opsForValue().set(key, objectMapper.writeValueAsString(authentication.getPrincipal()));

        redisTemplate.expire(key, Duration.ofMinutes(5));

        node.put("auth_token", token);

        response.getOutputStream().write(objectMapper.writeValueAsBytes(node));

    }
}
